﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zhaoxi.SqlSugar.Common;
using Zhaoxi.SqlSugar.Models;

namespace Zhaoxi.SqlSugarAdvanced
{
    public class ReadWriteSeparation
    {
        /// <summary>
        /// 读写分离 - cs端项目一般用不上 - 主要是再配置，并不难很简单。
        /// </summary>
        public static void Show()
        {
            ConnectionConfig connectionConfig = new ConnectionConfig()
            {
                ConnectionString = CustomConnectionConfig.ConnectionString001,
                IsAutoCloseConnection = true,
                DbType = DbType.SqlServer,
                // 读写分离的主从服务器的数据库连接配置
                SlaveConnectionConfigs = new List<SlaveConnectionConfig>()
                {
                    new SlaveConnectionConfig(){ 
                         HitRate= 200, // 指定从库查询的权重比例 - 这样可以根据服务器性能配置查询比例
                         ConnectionString=CustomConnectionConfig.ConnectionStringRead01, //从库1数据库链接字符串
                    },
                    new SlaveConnectionConfig(){
                         HitRate= 1000,// 指定从库查询的权重比例 - 这样可以根据服务器性能配置查询比例
                         ConnectionString=CustomConnectionConfig.ConnectionStringRead02//从库2数据库链接字符串
                    }
                }
            };

            //HitRate 权重的比例；
            using (SqlSugarClient db = new SqlSugarClient(connectionConfig))
            {

                db.Aop.OnLogExecuting = (sql, para) =>
                {
                    Console.WriteLine($"Sql语句：{sql}");
                };

                #region 插入数据同步到从库测试
                {
                    //db.Deleteable<Company>().ExecuteCommand(); 
                    //db.Insertable<Company>(new Company()
                    //{
                    //    CompanyName = "测试数据库读写分离",
                    //    CreateTime = DateTime.Now
                    //}).ExecuteCommand();

                    ////Company company = db.Queryable<Company>().First();
                    ////company.CompanyName = "New";
                    //db.Updateable<Company>(company).ExecuteCommand();
                }
                #endregion

                #region 测试从库查询的权重比例
                {
                    int writeBaseQueryCount = 0;
                    int queryBaseQueryCount01 = 0;
                    int queryBaseQueryCount02 = 0;

                    for (int i = 0; i < 100; i++)
                    {
                        Company company = db.Queryable<Company>().First();
                        if (company.CompanyName.Equals("测试数据库读写分离"))  //说明查询的是主库
                        {
                            writeBaseQueryCount = writeBaseQueryCount + 1;
                        }
                        else if (company.CompanyName.Equals("测试数据库读写分离--从库0001"))
                        {
                            queryBaseQueryCount01 = queryBaseQueryCount01 + 1;
                        }
                        else if (company.CompanyName.Equals("测试数据库读写分离--从库0002"))
                        {
                            queryBaseQueryCount02 = queryBaseQueryCount02 + 1;
                        }
                    }
                    Console.WriteLine($"共计100次查询，查询主库{writeBaseQueryCount}次； 从库01查询了{queryBaseQueryCount01}次 ； 从库02查询了{queryBaseQueryCount02}次");
                }
                #endregion

                #region 测试 - 主库到从库数据同步确实是有延迟的；
                //主库到从库数据同步确实是有延迟的；
                {
                    //db.Deleteable<Company>().ExecuteCommand();
                    //db.Insertable<Company>(new Company()
                    //{
                    //    CompanyName = "测试数据库20221129",
                    //    CreateTime = DateTime.Now,
                    //}).ExecuteCommand();

                    //db.Ado.IsDisableMasterSlaveSeparation = true; //查询不查询从库了，直接查询主库

                    //int i = 1;
                    //Stopwatch stopwatch = new Stopwatch();
                    //stopwatch.Start();
                    //while (true)
                    //{
                    //    Console.WriteLine($"当前是第{i}次查询~");
                    //    Company company = db.Queryable<Company>().First(c => c.CompanyName.Equals("测试数据库20221129"));
                    //    if (company != null) //说明已经查询到数据了，说明数据已经同步成功了
                    //    {
                    //        stopwatch.Stop();
                    //        Console.WriteLine($"数据同步成功~~数据同步共计消耗{stopwatch.ElapsedMilliseconds}ms");
                    //        break;
                    //    }
                    //    else
                    //    {
                    //        i++;
                    //        Thread.Sleep(100);
                    //    }
                    //}
                    //Console.Read();
                }
                //对于查询的数据及时性比价高；
                //希望插入的数据马上就能够查询出来；
                //1.业务妥协
                //2.直接查询主库
                #endregion
            }
        }
    }
}
